package vip.xiaonuo.dev.modular.sms.util.hkust;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import vip.xiaonuo.dev.api.DevConfigApi;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 消息工具类
 *
 * @author qinguangrui
 */
@Component
public class SendMsg {
    private static String SMS_CONFIG_URL;
    private static String SMS_CONFIG_ACCOUNTID;
    private static String SMS_CONFIG_ACCOUNTKEY;

    @Autowired
    private DevConfigApi devConfigApi;

    @PostConstruct
    public void init() {
        SMS_CONFIG_URL = devConfigApi.getValueByKey("SMS_CONFIG_URL");
        SMS_CONFIG_ACCOUNTID = devConfigApi.getValueByKey("SMS_CONFIG_ACCOUTID");
        SMS_CONFIG_ACCOUNTKEY = devConfigApi.getValueByKey("SMS_CONFIG_ACCOUNTKEY");
    }

    /**
     * 消息发送
     *
     * @param accountID  应用账号
     * @param accountKey 应用秘钥
     * @param msgJson    消息内容
     * @return JSONObject 发送结果
     * @author: qinguangrui
     */
    public static JSONObject sendMsg(String accountID, String accountKey, String msgJson) {
        List<BasicNameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("accountID", accountID));
        params.add(new BasicNameValuePair("accountKey", accountKey));
        params.add(new BasicNameValuePair("msgJson", msgJson));

        String result = HttpUtils.httpPostWithParms(SMS_CONFIG_URL + Constant.SEND_URL, params);
        return JSON.parseObject(result);
    }

    /**
     * 获取消息结果
     *
     * @param msgId 消息id
     * @return JSONObject 消息结果
     * @author: qinguangrui
     */
    public static JSONObject getMsgResult(String msgId) {
        String url = SMS_CONFIG_URL + Constant.MSG_RESULT_URL.replace("#accountID", SMS_CONFIG_ACCOUNTID)
                .replace("#accountKey", SMS_CONFIG_ACCOUNTKEY).replace("#msgId", msgId);
        String result = HttpUtils.httpGet(url);
        return JSON.parseObject(result);
    }

    /**
     * 从消息发送结果获取消息ID
     *
     * @param jsonObject 消息发送结果对象
     * @return Long 消息ID
     * @author: qinguangrui
     */
    public static Long getMsgId(JSONObject jsonObject) {
        if (Objects.isNull(jsonObject)) {
            return -1L;
        }
        if (Objects.equals(jsonObject.getInteger("errcode"), 0)) {
            return jsonObject.getLong("data");
        }
        return -1L;
    }
}
